﻿using Loong.AspNetCore.Mvc.Auditing;
using Loong.AspNetCore.Mvc.Uow;
using Loong.Auditing;
using Loong.Threading.Locks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Loong.Web.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    [Auditing]
    public class WeatherForecastController : ControllerBase
    {
        private readonly ILockFactory _lockFactory;

        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        public WeatherForecastController(ILockFactory lockFactory)
        {
            _lockFactory = lockFactory;
        }

        [HttpGet]
        [AllowAnonymous]
        [UnitOfWork(10000)]
        [DisableAuditing]
        public async Task<IEnumerable<WeatherForecast>> Get()
        {
            using (var locker = await _lockFactory.LockAsync("test", _lockFactory.GetOrCreateOwner(), TimeSpan.FromSeconds(10)))
            {
            }

            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}
